 /** 
 * @description 具备CRUD 操作的列表页面 ，在Rsd.view.ListPage 基础上添加modelType和schema属性
 * @description BizController 配合使用，有规定的参数格式
 * */
Rsd.define('Rsd.zen.page.BizListPage', {
    extend: 'Rsd.zen.page.ListPage',
    requires: ['Rsd.control.SearchToolBar', 'Rsd.form.ComboBoxEnum'],
    xtype: 'biz-list-page',
    readonly: false,
    form:{viewType:'Rsd.zen.dialog.BizFormDialog'},
    /**
     * @description 对象模型，用户于取Rsd.data.ModelSchema(集成了模型结构以及对象的CURD操作)对象
     * @description 优先从页面中获取，不存在时，从该页面菜单中获取
     */
    //modelType:'',
    /**
     * 对象类型结构 通过 Rsd.app.getSchema(modelType)获取
     */
    //modelSchema:null,
   
    /**
    *  @description 合并到父类属性 formFields后使用
    * */
    fields: [],
    /**
    *  @description 合并到父类属性 gridColumns后使用
    * */
    columns: [],

    /**
     *  @description 列表数据字段名
     */
    listMember: '',
    /**
     * 操作列
     */
    opColumns: [
        {
            name: 'edit',
            text: '操 作',
            nobr: true,
            width: 160,
            fixed: true,
            xtype: 'template',
            format: 'rowOpFormat'
        },
        {
            name: 'space',
            text: '',
            xtype: 'template',
            width: 5,
            fixed: true,
            hideable: false,
            sortable: false
        }
    ],
    /**
     * 
     */
    autoLoad: false,//不自动加载数据，点击查询按钮后加载
    /**
     *  @description 工具栏上 增加的按钮, [{text:'ok',handler:'btn_ok'}]
     */
    newButtons: [],
    /**
     * @description 操作列按钮,['edit','br','delete']
     * 元素支持类型：
     *   string:edit or delete ,
     *   object: 
     *      {
     *          text:'查看',
     *          image:'',
     *          express:'{{=name}}=="tom"',//计算表达式
     *          handler:function(){},
     *      }
     */
    opButtons: ['edit', 'delete'],
    /**
    * 
    * */
    constructor: function BizListPage(config) {
        config = config || {}; 
        this.apply(config); 
    },
    /**
     * 
     */
    initBySchema:function initBySchema()
    {
        var me = this;
         if(!me.modelSchema)
         {
            return;
         }
        if (me.gridColumns.length == 0) {
            //对已存在但列进行属性合并，对不存在列不会添加到原始数组中,可通过列的visible属性控制列的显示状态
            me.gridColumns = me.modelSchema.getColumns(me.columns || []); 
        }
        if (me.searchColumns.length == 0) {
            me.searchColumns = me.modelSchema.searchColumns;
        }
        if (me.sort.length == 0) {
            me.sort = me.modelSchema.sortColumns || [];
        }

        //设计模式参数设置
        if (me.mode == 'design') {
            me.modelSchema.columns.map((p) => {
                p['design'] = true;
                p['designHandler'] = function (col) {
                    if (me.designHandler) {
                        me.funApplyByIOC(me.designHandler, ["column", col])
                    }
                    else {
                        alert('属性designHandler未设置');
                    }
                };
            }); 
        }
    },
    /**
    * */
    onBeforeInit: function onBeforeInit() {

        this.callParent();

        var me = this; 
        if(!me.modelType)
        { 
            return;
        }
        console.log(JSON.stringify(me.modelType));
        me.schemaIsLoading = true;
        //handler 是cqrs 对象 
        me.handler.getSchema(function (modelSchema) { 
           me.modelSchema = modelSchema; 
           me.initBySchema(); 
           me.schemaIsLoading = false;
           me.fire('schemaLoaded',[modelSchema]);
       });
       
        //表格和表单的schema可能不一致，如：当表格是视图，表单是table时，form和list 的schema不一致
        //加载表单schema,
        if (this.form.modelType) {

            Rsd.app.getSchema(this.form.modelType, function (modelSchema) {

                me.formSchema = modelSchema; 

                if (me.formFields.length == 0) {
                    me.formFields = modelSchema.getFields(me.fields || []);
                }
            });
        }
 
        // if (Rsd.isString(this.toolBar)) {
        //     this.toolBar = Rsd.widget(this.toolBar);
        // }
        var curd = me.modelSchema && me.modelSchema.curd;
        if(me.formSchema)
        {
            curd = me.formSchema.curd;
        }
        if(me.readonly)
        {
            curd = 4;
        }
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
          
        var newBtns = me.newButtons;
 
        //新增权限 控制
        if((curd&1)===1 && me.newButtons.find(item=>item.handler == 'btn_newItem' || item.fn == 'btn_newItem')===undefined)
        {
            newBtns.splice(1,0,{text: '新 增', handler: 'btn_newItem' });
        } 
        //无新增权限，存在新增按钮（handler === 'btn_newItem'） 删除 

        //查询权限 控制
        if((curd&4)===4 && me.newButtons.find(item=>item.handler == '_btn_search' || item.fn == '_btn_search')===undefined)
        {
            newBtns.splice(0,0,{xtype:'button', text: '查 询' ,visible:true,margin: '0 5 0 10', width: 100, handler:'_btn_search'});
        }
        //无查询权限，存在查询按钮（handler === '_btn_search'） 删除 
  
        for(var i in me.newButtons)
        {
            if(me.newButtons[i] == 'new'|| me.newButtons[i] =='add')
            {
                me.newButtons[i] = { text: '新 增', handler: 'btn_newItem' }; 
            }
        }  
    },
    /**
    *
    * */
    onAfterInit: function onAfterInit() {

        this.callParent();
       
        //debugger;

        var me = this;
        var curd = me.modelSchema && me.modelSchema.curd;
        if(me.readonly)
        {
            curd = 4;
        }
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
         
        //操作列
        var hasOpBtn = false;
        var opBtns = this.opButtons || [];
        for (var i in opBtns) {
            var item = opBtns[i];
            if (Rsd.isString(item)) {

                if (item.toLowerCase() == 'edit' && (curd & 2)==2) {
                    hasOpBtn = true;
                    break;
                }

                if (item.toLowerCase() == 'delete' && (curd & 8)==8) {
                    hasOpBtn = true;
                    break;
                } 
                continue;
            } 
            hasOpBtn = true;
            break;
        }
        if(hasOpBtn==false)
        {
            this.opColumns = [{
                name: 'space',
                text: '',
                xtype: 'template',
                width: 5,
                fixed: true,
                hideable: false,
                sortable: false
            }];
        }
        //设计模式参数设置
        if (me.mode == 'design') {

            me.newButtons.push({
                xtype:'link',
                label:false,
                text:'添加按钮',
                width:'80px',
                style:{
                    cursor:'pointer',  
                    lineHeight: 25,
                    borderRadius: '40px',
                    backgroundColor: '#0c25eccc',
                    color: '#FFF',
                    textAlign: 'center'
                },
                handler:function(){
                    //
                    if(me.designHandler)
                    {
                        me.funApplyByIOC(me.designHandler,["button"])
                    }
                    else
                    {
                        alert('属性designHandler未设置');
                    }
                    
                }
            });

            //console.log('biz list design button',me.newButtons);
        }

        //查询添加列 
        for (var i in me.searchColumns) {
            var _c = me.searchColumns[i];
            _c.xtype = _c.xtype || 'text';
            _c.label = { content: _c.label || _c.text, height: 30 };
            _c.dataIndex = _c.dataIndex || _c.name;
            _c.name = _c.name || _c.dataIndex;
            _c.margin = _c.margin || "0 0 0 20";
        }
 
        if (me.mode == 'design') {
            
            me.searchColumns.push({
                xtype:'link',
                label:false,
                width:'90px',
                text:'添加筛选条件',
                style:
                {
                    cursor:'pointer',  
                    lineHeight: 25,
                    borderRadius: '40px',
                    backgroundColor: '#2dac08f0',
                    color: '#FFF',
                    textAlign: 'center'
                },
                handler:function(){
                    //
                    if(me.designHandler)
                    {
                        me.funApplyByIOC(me.designHandler,["search"])
                    }
                    else
                    {
                        alert('属性designHandler未设置');
                    } 
                }
            });

            //console.log('biz list design search',me.searchColumns.length);
        }
       
        //me.callParentFn('onBeforeRender');
       
        return this;
    },
    /*
    *
    * */
    load: function load(args, callback) {

        var me = this;
        if(me.isSchemaLoading)
        {
            me.on('schemaLoaded',function(){me.load(args,callback);});
        }
      
        var _args = args || {};
        var _fn_callback = function(data){
            if(callback)
            {
                callback(data);
            }
            me.____lastWhere = me.toolBar && me.toolBar.getWhere();
        };
        if(Rsd.isArray(_args))
        {
             me.callParentFn("load",[_args, _fn_callback]);
            return;
        }
        //数据源 属性
        if (this.dataSource) {
            me.callParentFn("load", [this.dataSource, _fn_callback]);
            return;
        } 
        //
        var _serviceName = me.serviceName || '';
        if(_serviceName)
        {
            var _service = Rsd.app.getService(_serviceName);
            me.dataStore = Rsd.create('Rsd.data.Store', { proxy: _service, listName: me.listMember || 'rows' });
            me.callParentFn("load", [_args, _fn_callback]);
            return;
        }
        //dataStore对象,Rsd.data.Store数据源，支持本地数据已本地缓存数据
        if (me.dataStore) {
            me.callParentFn("load", [_args, _fn_callback]);
            return;
        }
        
        //cqrs  
        var opt  = me.getPagingOpt();
        var _args = Rsd.apply(args||{}, {
            modelType: me.modelType || '',
            pageSize: opt.pageSize || 100,
            pageIndex: opt.pageIndex || 0,
        });
        _args.where = Rsd.arrayConcat(_args.where,me.where, me.toolBar && me.toolBar.getWhere()),
        _args.sort = Rsd.arrayConcat(_args.sort, me.sort); 
        
        me.handler.list(_args,callback); 
        
        return this;
    },

    /**
     * @description 最后操作列格式化
     */
    rowOpFormat: function rowOpFormat(row) {

        if (this.readonly) {
            return [];
        }
        var me = this;
        var curd = me.modelSchema && me.modelSchema.curd;
        if(me.readonly)
        {
            curd = 4;
        }
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        var btns = [];
        var opBtns = this.opButtons || [];
        for (var i in opBtns) {
            var item = opBtns[i];
            if (Rsd.isString(item)) {

                if (item.toLowerCase() == 'edit') {
                    if((curd & 2)==2)
                    {
                        var btnEdit = me.editButton(row);
                        btns.push(btnEdit);
                    } 
                    continue;
                }

                if (item.toLowerCase() == 'delete') {
                    if((curd & 8)==8)
                    {
                        var btnDel = me.deleteButton(row);
                        btns.push(btnDel);
                    } 
                    continue;
                }

                if (item.toLowerCase() == 'br') {
                    btns.push(document.createElement('br'));
                    continue;
                }
                continue;
            }

            if (Rsd.isObject(item)) {
                //根据 计算表达 展示按钮
                var express = item.express;
                if (Rsd.isEmpty(express) || eval(Rsd.template(express, row))) {
                    var _fn = item.handler || item.onclick || item.fn;
                    var btn = document.createElement(_fn?'a':'label'); 
                    btn.innerHTML = item.text;
                    btn.style.display = 'inline-table';
                    btn.style.width = '45px';
                    btn.style.textAlign = "right";
                    btn.style.margin = "0 5px 0 5px";
                    if(item.image || item.img)
                    {
                        btn.style.backgroundImage = 'url(' + item.image || item.img + ')';
                        btn.style.backgroundPosition = 'left center';
                        btn.style.backgroundSize = '12px';
                        btn.style.backgroundRepeat = 'no-repeat';
                    } 
                    if(_fn)
                    {  
                        btn.href = '#';
                        btn.handler = _fn;
                        btn.onclick = function () { 
                            me.funApplyByIOC(this.handler, [row, me]);
                        };
                    }
                   
                    btns.push(btn);
                }

                continue;
            }
        }

        return btns;
    },
    /**
     * 
     * @param {*} row 
     * @param {*} style 
     * @returns 
     */
    editButton: function editButton(row,style) {
        var me = this;
        var btnEdit = document.createElement('a');
        btnEdit.href = '#';
        btnEdit.innerHTML = '修改';
        btnEdit.style.display = 'inline-table';
        btnEdit.style.width = '45px';
        btnEdit.style.textAlign = "right";
        btnEdit.style.margin = "0 5px 0 5px";
        btnEdit.style.backgroundImage = 'url(' + Rsd.getRedjsHost() + "/resources/svg/update.svg" + ')';
        btnEdit.style.backgroundPosition = 'left center';
        btnEdit.style.backgroundSize = '12px';
        btnEdit.style.backgroundRepeat = 'no-repeat';
        me.setElStyle(btnEdit,style);
        btnEdit.onclick = function () { 
            me.editItem(row);
        };

        return btnEdit;
    },
    /**
     * 
     * @param {*} row 
     * @param {*} style 
     * @returns 
     */
    deleteButton: function deleteButton(row,style) {

        var me = this;
        var btnDel = document.createElement('a'); 
        btnDel.href = '#';
        btnDel.innerHTML = '删除';
        btnDel.style.display = 'inline-table';
        btnDel.style.width = '45px';
        btnDel.style.textAlign = "right";
        btnDel.style.margin = "0 5px 0 5px";
        btnDel.style.backgroundImage = 'url(' + Rsd.getRedjsHost() + "/resources/svg/delete.svg" + ')';
        btnDel.style.backgroundPosition = 'left center';
        btnDel.style.backgroundSize = '12px';
        btnDel.style.backgroundRepeat = 'no-repeat';
        me.setElStyle(btnDel,style);
        btnDel.onclick = function () {
            me.deleteItem(row);
        };
        return btnDel;
    },
    
    /**
     *  @description 用于绑定按钮事件
     */
    btn_newItem: function btn_newItem(btn, evt) {  
        //console.error('btn_newItem',btn);   
        this.newItem(this.form.data||{});////form.data 新增时表单data默认值
    },
    /**
    * @description 查看对象
     * */
    viewItem: function viewItem(record) {
        //调用父类方法
        this.showItem(record || {}, true);
    },
    /**
     * @description 新增对象
     * @param record 新增对象的默认信息
     */
    newItem: function newItem(record) {
        //调用父类方法
        if(record && record.$className == "Rsd.form.Button")
        {
            Rsd.alert("[新增]按钮应绑定btn_newItem事件");
            return;
        }
        this.showItem(record || {}, false);
    },
    /**
     * @description 编辑对象
     *  */
    editItem: function editItem(record) {

        //调用父类方法
        this.showItem(record || {}, false);
    },

    /**
     * @description 删除
     * */
    deleteItem: function (record) {
        var me = this;
        if (record == null) {
            return;
        }

        if (confirm('确认删除该记录?')) {

             //指定方法
            if (me.deleteHandler) {
                
                me.funApplyByIOC(me.deleteHandler,[record,callback]);
                return;
            }

            //指定接口服务
            if (me.deleteServiceName) {

                Rsd.app.getService(me.deleteServiceName).request(record, function (resp) {

                    if (resp.success) {

                        if (callback) {
                            callback();
                        }

                        Rsd.showPopup("删除成功。");
                        return false;//flase 表示拒绝后续拦截方法的处理
                    } else {
                        Rsd.alert('数据删除失败', resp.msg);
                        return false;//flase 表示拒绝后续拦截方法的处理
                    }
                });

                return;
            }

            //cqrs
            me.handler.delete(record,function(resp){
                me.load(); 
            });
        }

    },
    /*
     * */
    rowDblClick: function rowDblClick(row, evt) {
        if (this.readonly) { 
            this.viewItem(row);
        } else {
            this.editItem(row);
        } 
    },
    /**
     * 
     * @param {*} row 
     * @param {*} readonly 
     * @returns 
     */
    createFormDialog: function createFormDialog(row, readonly) {
        var form = this.callParentFn('createFormDialog', [row, readonly]);
        form.serviceName = this.form.serviceName || null;
        form.saveHandler = this.form.saveHandler || null;
        return form;
    }

}, function (type) {
    //modelType
    var _modelTypeGetter = function () {
 
        return this.__modelType;
    };
    var _modelTypeSetter = function (value) {

        this.__modelType = value;

    };
    //biz.list 接口参数modelType
    this.defineProperty(type, "modelType", _modelTypeGetter, _modelTypeSetter, false);

    //biz.list 接口参数sort
    this.defineProperty(type, 'sort', function () { return this.__sort || []; }, function (sort) {
        this.__sort = sort;
    }, true);
    //biz.list 接口参数where
    this.defineProperty(type, 'where', function () { return this.__where || []; }, function (where) {
        this.__where = where;
    }, true);

    var _handlerGetter = function () {

        if (!this.__handler) {
            this.__handler = Rsd.create('Rsd.cqrs.List', {owner: this });
        }
        return this.__handler;

    };

    var _handlerSetter = function (value) {

        if (Rsd.isString(value)) {
            this.__handler = Rsd.widget(value, {owner: this });;
            return;
        }
        this.__handler = value;
    }

    this.defineProperty(type, "handler", _handlerGetter, _handlerSetter, true);
});